<template>
  <div class="com-box">
    <div class="common-title">
      日间申请
    </div>
    <div class="apply-form" v-loading="state.formLoading">
      <el-form ref="form" :model="formdata" :rules="rules" label-width="80px" label-position="left" size="default">
        <div class="form-sub-title">就诊信息</div>
        <div class="form-box">
          <el-form-item label="患者姓名" prop="name" inline>
            <el-input v-model="formdata.patient.name" placeholder="请输入患者姓名" size="default"></el-input>
          </el-form-item>

          <el-form-item label="患者性别" prop="gender" inline>
            <el-select v-model="formdata.patient.gender" placeholder="请选择患者性别" size="default" clearable
              style="width:100%;">
              <el-option v-for="(k, v) in sexObj" :key="k" :label="k" :value="v"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="年龄" prop="age" inline>
            <el-input-number v-model="formdata.patientRecord.age" :min="0" size="default" style="width:100%;" />
          </el-form-item>

          <el-form-item label="身份证号" prop="identity" inline>
            <el-input v-model="formdata.patient.identity" placeholder="请输入身份证号" size="default"></el-input>
          </el-form-item>

          <el-form-item label="联系方式" prop="phone" inline>
            <el-input v-model="formdata.patient.phone" placeholder="请输入联系方式" size="default"></el-input>
          </el-form-item>

          <el-form-item label="就诊科室" prop="visitingDepartment" inline>
            <el-select v-model="formdata.patientRecord.visitingDepartmentId" placeholder="请选择就诊科室" size="default"
              clearable filterable remote :remote-method="jzksRemoteMethod" style="width:100%;"
              @change="visitingDepartmentChange">
              <el-option v-for="(item, index) in state.departmentList" :key="index" :label="item.departmentName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="就诊医生" prop="visitingDoctor" inline>
            <el-select v-model="formdata.patientRecord.visitingDoctorId" placeholder="请选择就诊医生" size="default" clearable
              filterable remote :remote-method="jzysRemoteMethod" style="width:100%;">
              <el-option v-for="(item, index) in state.visitingDoctorList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="入院诊断" prop="preDiagnosis" inline>
            <!-- <el-select v-model="formdata.patientRecord.preDiagnosis" placeholder="请选择入院诊断" size="default" clearable filterable style="width:100%;">
              <el-option v-for="(item, index) in state.diagnosisList" :key="index" :label="item.name"
                :value="item.name"></el-option>
            </el-select> -->
            <el-input v-model="formdata.patientRecord.preDiagnosis" placeholder="请输入入院诊断" style="width:100%"
              size="default"></el-input>
          </el-form-item>
        </div>

        <div class="form-sub-title">手术信息</div>
        <div class="form-box">
          <el-form-item label="手术科室" prop="operationDepartment" inline>
            <el-select v-model="formdata.patientRecordOperation.departmentId" placeholder="请选择手术科室" size="default"
              clearable filterable remote :remote-method="ssksRemoteMethod" style="width:100%;"
              @change="opDepartmentChange">
              <el-option v-for="(item, index) in state.opDepartmentList" :key="index" :label="item.departmentName"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="入院病区" prop="hospitalAreaId" inline>
            <el-select v-model="formdata.patientRecord.hospitalAreaId" placeholder="请选择入院病区" size="default" clearable
              filterable style="width:100%;" @change="opAreaChange">
              <el-option v-for="(item, index) in state.hospitalAreaList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="术前诊断" prop="diagnosis" inline>
            <el-select v-model="formdata.patientRecordOperation.diagnosis" placeholder="请选择术前诊断" size="default" clearable style="width:100%;">
              <el-option v-for="(item, index) in state.diagnosisList" :key="index" :label="item.name"
                :value="item.name"></el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item label="主刀医生" prop="chiefDoctor" inline>
            <el-select v-model="formdata.patientRecordOperation.chiefDoctorId" placeholder="请选择主刀医生" size="default"
              style="width:100%;" clearable filterable remote :remote-method="zdysRemoteMethod"
              @change="opChiefDoctorChange">
              <el-option v-for="(item, index) in state.chiefDoctorList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="联系电话" prop="chiefDoctorPhone" inline>
            <el-input v-model="formdata.patientRecordOperation.chiefDoctorPhone" placeholder="请输入主刀医生联系电话"
              size="default"></el-input>
          </el-form-item>

          <el-form-item label="拟行手术" prop="operationId" inline>

            <!-- <el-select v-model="formdata.patientRecordOperation.operationId" placeholder="请选择拟行手术" size="default" style="width:100%;"
              clearable filterable> 
              <el-option v-for="(item, index) in state.operationList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select> -->
            <el-select-v2 v-model="formdata.patientRecordOperation.operationId" :options="state.operationList" clearable
              filterable remote :remote-method="opRemoteMethod" size="default" v-loading="state.opSelectLoading"
              placeholder="请通过搜索来选择拟行手术" style="width:100%;">
            </el-select-v2>
          </el-form-item>

          <el-form-item label="麻醉医生" prop="anaesthetistId" inline>
            <el-select v-model="formdata.patientRecordAnesthesiaAssessment.anaesthetistId" placeholder="请选择麻醉医生"
              style="width:100%;" size="default" clearable filterable>
              <el-option v-for="(item, index) in state.anesthesiaDoctorList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="拟行麻醉" prop="anesthesiaModeId" inline>
            <el-select v-model="formdata.patientRecordAnesthesiaAssessment.anesthesiaModeId" placeholder="请选择拟行麻醉"
              style="width:100%;" size="default" clearable filterable>
              <el-option v-for="(item, index) in state.anesthesiaModeList" :key="index" :label="item.name"
                :value="item.id"></el-option>
            </el-select>
          </el-form-item>



        </div>

      </el-form>

      <div class="btn-list flex justify-end">
        <el-button type="primary" size="default" @click="saveForm()">
          保存
        </el-button>
        <el-button type="success" size="default" @click="saveForm()">
          申请
        </el-button>
        <el-button type="default" size="default" @click="resetForm()">
          撤销
        </el-button>
      </div>

    </div>
  </div>
</template>

<script setup name="applyDaily">
import { toolsApi } from '/@/api/tools'
import { dsApi } from '/@/api/ds/index';
import { ElMessageBox, ElMessage } from 'element-plus'
import { usePatientDetail } from '/@/stores/patientDetail';
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router';
const stores = usePatientDetail();
const { sexObj } = storeToRefs(stores);
const router = useRouter();

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);


const props = defineProps({
  datas: {
    type: Object,
    default: () => { },
  },
  dtid: {
    type: String,
    default: ''
  }
});
const state = reactive({
  departmentList: [],
  departmentApiData: {
    search: ''
  },
  opDepartmentList: [], // 手术科室
  opDepartmentApiData: {
    search: ''
  },
  hospitalAreaList: [],
  diagnosisList: [],
  operationList: [],
  anesthesiaModeList: [],
  formLoading: false,
  operationApiData: {
    departmentId: null,
    doctorId: null,
    search: ''
  },
  visitingDoctorApiData: {
    chiefStatus: null,
    hospitalAreaId: null,
    departmentId: null,
    search: ''
  },
  visitingDoctorList: [], // 就诊医生列表

  chiefDoctorApiData: {
    chiefStatus: 1,
    hospitalAreaId: null,
    departmentId: null,
    search: ''
  },
  chiefDoctorList: [], // 主刀医生列表

  anesthesiaDoctorList: [], // 麻醉医生列表
  opSelectLoading: false
})
const formdata = reactive({
  prid: '',
  patient: {
    name: '',
    gender: '',
    identity: '',
    phone: '',
  },
  patientRecord: {
    age: '',
    visitingDoctorId: '', // 就诊医生
    visitingDepartmentId: '', // 就诊科室
    preDiagnosis: '', // 入院诊断
    hospitalAreaId: '1', // 病区
  },
  patientRecordOperation: {
    departmentId: '', // 手术科室
    diagnosis: "", //术前诊断
    operationId: "", // 拟行手术
    chiefDoctorId: "", // 主刀医生
    chiefDoctorPhone: "", // 主刀医生联系方式
  },
  patientRecordAnesthesiaAssessment: {
    anesthesiaModeId: '', // 麻醉方式id
    anaesthetistId: '', // 麻醉医生id
  }
})

const route = useRoute();

// 页面加载时
onMounted(() => {

  formdata.prid = route.query.id?route.query.id:props.dtid

  setFormDatas()
  getDepartments()
  getOpDepartments()
  getHospitalArea()
  getDiagnosisList()
  getAnesthesiaModeList()

  getVisitingDoctors() // 获取就诊医生
  getChiefDoctors() // 获取主刀医生
  getAnesthesiaDoctors() // 获取麻醉医生
});

// 科室下拉
const getDepartments = () => {
  toolsApi().departmentList(state.departmentApiData).then(res => {
    state.departmentList = res.data
  })
}

// 就诊科室远程搜索
const jzksRemoteMethod = (query) => {
  if (query) {
    state.departmentApiData.search = query
  } else {
    state.departmentApiData.search = ''
  }
  getDepartments()
}

// 手术科室下拉
const getOpDepartments = () => {
  toolsApi().departmentList(state.opDepartmentApiData).then(res => {
    state.opDepartmentList = res.data
  })
}

// 手术科室远程搜索
const ssksRemoteMethod = (query) => {
  if (query) {
    state.opDepartmentApiData.search = query
  } else {
    state.opDepartmentApiData.search = ''
  }
  getOpDepartments()
}


const visitingDepartmentChange = (val) => {
  if (val) {
    state.visitingDoctorApiData.departmentId = val
  } else {
    state.visitingDoctorApiData.departmentId = null
  }
  formdata.patientRecord.visitingDoctorId = ''
  getVisitingDoctors()
}

// 就诊医生远程搜索
const jzysRemoteMethod = (query) => {
  if (query) {
    state.visitingDoctorApiData.search = query
  } else {
    state.visitingDoctorApiData.search = ''
  }
  getVisitingDoctors()
}

const getVisitingDoctors = () => {
  toolsApi().doctorList(state.visitingDoctorApiData).then(res => {
    state.visitingDoctorList = res.data
  })
}


// 主刀医生远程搜索
const zdysRemoteMethod = (query) => {
  if (query) {
    state.chiefDoctorApiData.search = query
  } else {
    state.chiefDoctorApiData.search = ''
  }
  getChiefDoctors()
}

const getChiefDoctors = () => {
  toolsApi().doctorList(state.chiefDoctorApiData).then(res => {
    state.chiefDoctorList = res.data
  })
}

const getAnesthesiaDoctors = () => {
  toolsApi().getAnesthesiaDoctorList().then(res => {
    state.anesthesiaDoctorList = res.data
  })
}




// 手术信息 科室change
const opDepartmentChange = (val) => {
  if (val) {
    state.chiefDoctorApiData.departmentId = val
    state.operationApiData.departmentId = val
  } else {
    state.chiefDoctorApiData.departmentId = null
    state.operationApiData.departmentId = null
  }
  getChiefDoctors()
  getOperationList()
  formdata.patientRecordOperation.chiefDoctorId = ''
  formdata.patientRecordOperation.operationId = ''
}


// 病区change
const opAreaChange = (val) => {
  // if (val) {
  //   state.chiefDoctorApiData.hospitalAreaId = val
  // } else {
  //   state.chiefDoctorApiData.hospitalAreaId = null
  // }
  // getChiefDoctors()
  // formdata.patientRecordOperation.chiefDoctorId = ''
}

const opChiefDoctorChange = (val) => {
  if (val) {
    state.operationApiData.doctorId = val
  } else {
    state.operationApiData.doctorId = null
  }
  getOperationList()
  formdata.patientRecordOperation.operationId = ''
}

// 病区下拉
const getHospitalArea = () => {
  toolsApi().hospitalArea().then(res => {
    state.hospitalAreaList = res.data
  }).catch(() => {
  })
}

// 诊断下拉
const getDiagnosisList = () => {
  toolsApi().diagnosisList().then(res => {
    state.diagnosisList = res.data
  }).catch(() => {
  })
}

// 手术远程搜索
const opRemoteMethod = (query) => {
  if (query) {
    state.operationApiData.search = query
  } else {
    state.operationApiData.search = ''
  }
  getOperationList()
}


// 手术下拉
const getOperationList = () => {
  state.opSelectLoading = true
  toolsApi().operationList(state.operationApiData).then(res => {
    state.opSelectLoading = false
    res.data.forEach(item => {
      item.label = item.name
      item.value = item.id
    })
    state.operationList = res.data
  }).catch(() => {
    state.opSelectLoading = false
  })
}

// 麻醉下拉
const getAnesthesiaModeList = () => {
  toolsApi().anesthesiaModeList().then(res => {
    state.anesthesiaModeList = res.data
  }).catch(() => {
  })
}

const saveForm = () => {
  ElMessageBox.confirm(`确认保存吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {

      dsApi().updatePatientRecord(formdata).then(res => {
        ElMessage.success('操作成功');
        emit('refresh');
      })
    })
    .catch(() => { });
}

const resetForm = () => {
  ElMessageBox.confirm(`确认撤销该患者吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      revokePatient()
    })
    .catch(() => { });

}

const revokePatient = () => {
  dsApi().revokePatient({ prid: formdata.prid }).then(res => {
    ElMessage.success('操作成功');
    router.push({
      path: '/dsProcess/overview',
    });
  })
}

const setFormDatas = () => {

  state.formLoading = true
  dsApi().recordDetail({ prid: formdata.prid }).then(res => {

    formdata.patient.name = res.data.patient ? res.data.patient.name : ''
    formdata.patient.gender = res.data.patient ? String(res.data.patient.gender) : ''
    formdata.patientRecord.age = res.data.age
    formdata.patient.identity = res.data.patient ? res.data.patient.identity : ''
    formdata.patient.phone = res.data.patient ? res.data.patient.phone : ''
    formdata.patientRecord.visitingDepartmentId = res.data.visitingDepartmentId
    formdata.patientRecord.visitingDoctorId = res.data.visitingDoctor ? res.data.visitingDoctor.id : ''
    formdata.patientRecord.preDiagnosis = res.data.preDiagnosis
    formdata.patientRecordOperation.departmentId = res.data.operation ? res.data.operation.departmentId : ''
    formdata.patientRecord.hospitalAreaId = res.data.hospitalAreaId
    formdata.patientRecordOperation.diagnosis = res.data.operation ? res.data.operation.diagnosis : ''
    formdata.patientRecordOperation.operationId = res.data.operation ? res.data.operation.operationId : ''
    formdata.patientRecordOperation.chiefDoctorId = res.data.operation ? res.data.operation.chiefDoctorId : ''
    formdata.patientRecordOperation.chiefDoctorPhone = res.data.operation ? res.data.operation.chiefDoctorPhone : ''
    formdata.patientRecordAnesthesiaAssessment.anesthesiaModeId = res.data.anesthesiaAssessment ? res.data.anesthesiaAssessment.anesthesiaModeId : ''
    formdata.patientRecordAnesthesiaAssessment.anaesthetistId = res.data.anesthesiaAssessment && res.data.anesthesiaAssessment.anaesthetist ? res.data.anesthesiaAssessment.anaesthetist.id : ''
    state.operationApiData.doctorId = res.data.operation ? res.data.operation.chiefDoctorId : ''
    getOperationList()
    state.formLoading = false


  }).catch(() => {
    state.formLoading = false
  })




}




</script>

<style lang="scss" scoped>
.apply-form {
  padding: 0 15px;
  min-height: 370px;
}

.el-form-item {
  align-items: center;
}

.el-form-item:last-of-type {
  margin-bottom: 20px !important;
}

.com-box {
  min-height: 620px;
}

.form-sub-title {
  color: #333;
  font-size: 14px;
  font-weight: bold;
  margin: 20px 0 15px;
}

.form-box {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 0 20px;
}

.btn-list {
  margin-top: 50px;

  .el-button {
    width: 100px;
  }
}</style>
